﻿using Microsoft.AspNet.Membership.OpenAuth;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace StockTradier.Account
{
    public partial class AccessToken : System.Web.UI.Page
    {
        protected string Code
        {
            get { return (string)Request.QueryString["Code"] ?? string.Empty; }
            private set { Request.QueryString["Code"] = value; }
        }

        protected string ConsumerKey
        {
            get { return ConfigurationManager.AppSettings["ConsumerKey"] ?? string.Empty; }
        }

        protected string ConsumerSecret
        {
            get { return ConfigurationManager.AppSettings["ConsumerSecret"] ?? string.Empty; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Code))
            {
                ObtainAccessToken();
            }
        }

        private void ObtainAccessToken()
        {
            try
            {
                RestClient client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/oauth/accesstoken", Method.POST);

                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("{0}:{1}", ConsumerKey, ConsumerSecret));
                string authorization = Convert.ToBase64String(plainTextBytes);

                request.AddHeader("Content-type", "application/x-www-form-urlencoded");
                request.AddHeader("Authorization", authorization);

                request.AddParameter("code", Code);
                request.AddParameter("grant_type", "authorization_code");

                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                string accessToken = (string)json["access_token"];

                GetUserProfile(accessToken);

            }
            catch (Exception)
            {

                throw;
            }
        }

        private void GetUserProfile(string accessToken)
        {
            try
            {
                RestClient client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/user/profile", Method.GET);

                request.AddHeader("Authorization", "Bearer " + accessToken);
                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                string name = (string)json["profile"]["name"];
                string id = (string)json["profile"]["id"];
                System.Web.HttpCookie myCookie = new System.Web.HttpCookie("Info");

                myCookie.Values.Add("name", name);
                myCookie.Values.Add("id", id);
                myCookie.Values.Add("accessToken", accessToken);

                myCookie.Expires.AddHours(24);

                Response.Cookies.Add(myCookie);

                RedirectToReturnUrl();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void RedirectToReturnUrl()
        {
            var returnUrl = Request.QueryString["ReturnUrl"];
            if (!String.IsNullOrEmpty(returnUrl) && OpenAuth.IsLocalUrl(returnUrl))
            {
                Response.Redirect(returnUrl);
            }
            else
            {
                Response.Redirect("~/");
            }
        }
    }
}